using ZYFramework.AudioSystem;
using Cysharp.Threading.Tasks;
using UnityEngine;
using UnityEngine.Audio;

namespace ZYFramework.AudioSystem.Samples
{
    /// <summary>
    /// 音频系统基础使用样例
    /// 演示2D音效、3D音效、BGM的基本播放方式
    /// </summary>
    public class AudioSystemBasicExample : MonoBehaviour
    {
        protected AudioManager_Entity audioManager;

        [Header("测试音频名称")]
        [SerializeField] private string test2DAudioName = "BulletFire";
        [SerializeField] private string test3DAudioName = "Footstep";
        [SerializeField] private string testBGMName = "GameMain";

        [Header("测试设置")]
        [SerializeField] private bool autoPlayOnStart = false;
        [SerializeField] private float autoPlayInterval = 2f;

        private float _lastAutoPlayTime;

        private void Start()
        {
            if (autoPlayOnStart)
            {
                _lastAutoPlayTime = Time.time;
            }
            Init_AudioManagerEntity();
        }

        protected void Init_AudioManagerEntity()
        {
            // 配置框架
            var config = new AudioConfig
            {
                ResourcePackageName = "HotRes",  // YooAsset资源包名
                BGMPathPrefix = "Assets/Audio/BGM/",
                SFXPathPrefix = "Assets/Audio/SFX/",
                AudioMixer = Resources.Load<AudioMixer>("AudioMixer"), // 加载AudioMixer资源

                // 对象池配置
                PoolInitSize_2D = 10,
                PoolMaxSize_2D = 30,
                PoolInitSize_3D = 15,
                PoolMaxSize_3D = 50,

                // 其他配置
                PreloadAllBGM = true,
                BGMFadeTime = 0.5f
            };

            GameObject audioManagerObj = new GameObject("AudioManager");
            audioManager = audioManagerObj.AddComponent<AudioManager_Entity>();
            audioManager.Initialization(config);
        }

        private void Update()
        {
            // 自动播放测试
            if (autoPlayOnStart && Time.time - _lastAutoPlayTime > autoPlayInterval)
            {
                TestPlay2D();
                _lastAutoPlayTime = Time.time;
            }

            // 键盘测试
            if (Input.GetKeyDown(KeyCode.Alpha1))
            {
                TestPlay2D();
            }

            if (Input.GetKeyDown(KeyCode.Alpha2))
            {
                TestPlay3D();
            }

            if (Input.GetKeyDown(KeyCode.Alpha3))
            {
                TestPlayBGM();
            }

            if (Input.GetKeyDown(KeyCode.Alpha4))
            {
                TestStopAll();
            }
        }

        /// <summary>
        /// 测试播放2D音效
        /// </summary>
        [ContextMenu("测试播放2D音效")]
        public void TestPlay2D()
        {
            // 简化API
            AudioManager_Entity.Instance.PlaySFX(test2DAudioName);
            Debug.Log($"[示例] 播放2D音效: {test2DAudioName}");
        }

        /// <summary>
        /// 测试播放3D音效
        /// </summary>
        [ContextMenu("测试播放3D音效")]
        public void TestPlay3D()
        {
            // 绑定到当前GameObject的Transform
            AudioManager_Entity.Instance.Play3DSFX(test3DAudioName, transform);
            Debug.Log($"[示例] 播放3D音效: {test3DAudioName}, 位置: {transform.position}");
        }

        /// <summary>
        /// 测试播放BGM
        /// </summary>
        [ContextMenu("测试播放BGM")]
        public async void TestPlayBGM()
        {
            // 检查Instance是否已初始化
            if (AudioManager_Entity.Instance == null)
            {
                Debug.LogError("[示例] AudioManagerEntity.Instance为null，请确保音频系统已正确初始化");
                return;
            }

            // 检查是否已初始化完成
            if (audioManager == null)
            {
                Debug.LogError("[示例] AudioManagerEntity未初始化，请先调用Init_AudioManagerEntity()");
                return;
            }

            var param = AudioPlayParams.Create2D(
                volume: 0.7f,
                pitch: Random.Range(0.9f, 1.1f), // 随机音调
                priority: AudioPriority.Normal
            );

            // 异步播放BGM（支持淡入淡出）
            await AudioManager_Entity.Instance.PlayBGMAsync(testBGMName, param);
            Debug.Log($"[示例] 播放BGM: {testBGMName}");
        }

        /// <summary>
        /// 测试停止所有音效
        /// </summary>
        [ContextMenu("测试停止所有音效")]
        public void TestStopAll()
        {
            AudioManager_Entity.Instance.StopAllSFX();
            Debug.Log("[示例] 停止所有SFX");
        }

        /// <summary>
        /// 测试自定义参数播放2D音效
        /// </summary>
        [ContextMenu("测试自定义参数2D音效")]
        public async void TestPlay2DWithParams()
        {
            var param = AudioPlayParams.Create2D(
                volume: 0.7f,
                pitch: Random.Range(0.9f, 1.1f), // 随机音调
                loop: false,
                priority: AudioPriority.High
            );

            await AudioManager_Entity.Instance.PlaySFX2DAsync(test2DAudioName, param);
            Debug.Log($"[示例] 播放2D音效（自定义参数）: {test2DAudioName}");
        }

        /// <summary>
        /// 测试自定义参数播放3D音效
        /// </summary>
        [ContextMenu("测试自定义参数3D音效")]
        public async void TestPlay3DWithParams()
        {
            var param = AudioPlayParams.Create3D(
                volume: 1f,
                minDistance: 5f,
                maxDistance: 15f,
                priority: AudioPriority.Normal
            );

            await AudioManager_Entity.Instance.PlaySFX3DAsync(test3DAudioName, transform, param);
            Debug.Log($"[示例] 播放3D音效（自定义参数）: {test3DAudioName}");
        }

        private void OnGUI()
        {
            GUILayout.BeginArea(new Rect(10, 10, 300, 200));
            GUILayout.Label("=== 音频系统基础示例 ===");
            GUILayout.Label("按 1 - 播放2D音效");
            GUILayout.Label("按 2 - 播放3D音效");
            GUILayout.Label("按 3 - 播放BGM");
            GUILayout.Label("按 4 - 停止所有SFX");
            GUILayout.EndArea();
        }
    }
}
